import { NextResponse, NextRequest } from 'next/server';
import { prisma } from '@/lib/db';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';

// GET /api/projects - 获取当前用户的所有项目
export async function GET(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session?.user?.id) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const userId = session.user.id;

    // 获取用户参与的所有项目
    const projectUsers = await prisma.projectUser.findMany({
      where: { userId },
      include: {
        project: {
          include: {
            tasks: {
              select: {
                id: true,
                status: true,
              },
            },
          },
        },
      },
    });

    // 处理项目数据，添加任务统计信息
    const projects = projectUsers.map(({ project }) => {
      const completedTasks = project.tasks.filter(task => task.status === 'DONE').length;
      return {
        id: project.id,
        name: project.name,
        description: project.description,
        status: project.tasks.length > 0 
          ? completedTasks === project.tasks.length 
            ? 'completed' 
            : 'in-progress' 
          : 'planning',
        tasks: {
          total: project.tasks.length,
          completed: completedTasks
        }
      };
    });

    return NextResponse.json(projects);
  } catch (error) {
    console.error('获取项目失败:', error);
    return NextResponse.json(
      { error: '获取项目时出错' },
      { status: 500 }
    );
  }
}

// POST /api/projects - 创建新项目
export async function POST(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session?.user?.id) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const userId = session.user.id;
    const body = await request.json();

    // 验证请求数据
    const { name, description } = body;
    if (!name) {
      return NextResponse.json({ error: '项目名称是必填的' }, { status: 400 });
    }

    // 创建项目并添加当前用户为所有者
    const project = await prisma.$transaction(async (tx) => {
      // 创建项目
      const newProject = await tx.project.create({
        data: {
          name,
          description
        }
      });

      // 添加用户为项目所有者
      await tx.projectUser.create({
        data: {
          userId,
          projectId: newProject.id,
          role: 'OWNER'
        }
      });

      // 创建活动记录
      await tx.activity.create({
        data: {
          userId,
          type: 'project_created',
          entityId: newProject.id,
          data: { projectName: name }
        }
      });

      return newProject;
    });

    // 格式化响应数据
    const formattedProject = {
      id: project.id,
      name: project.name,
      description: project.description,
      status: 'planning',
      tasks: {
        total: 0,
        completed: 0
      }
    };

    return NextResponse.json(formattedProject, { status: 201 });
  } catch (error) {
    console.error('创建项目失败:', error);
    return NextResponse.json(
      { error: '创建项目时出错' },
      { status: 500 }
    );
  }
} 